import { Models } from '../common/typings/model'
import HttpException from '../core/HttpException'
/**
 * 数据校验中间件
 */
function validator(validateFunc: Function, type: 'query' | 'body' = 'query') {
  return async function validator(ctx: Models.Ctx, next: Function) {
    let data = ctx.request.query
    if (type === 'body') {
      data = ctx.request.body
    }
    const error: Error | null = validateFunc(data) || null
    if (error) {
      console.log('数据校验失败')
      //校验失败
      ctx.body = new HttpException.ParameterException(error.message)
      return
    }
    await next()
  }
}
export default validator
